const express = require('express');
const router = express.Router();
const { no, ok } = require('../../utils/utlis');
const { cosUpload, cosBatchUpload } = require('../../utils/oss');
const DB = require('../../utils/db');
const { getDateTime } = require('../../utils/utlis');
const path = require('path');

// 文件上传
const multer = require('multer');

const storageSign = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, path.join(__dirname, '../../public/uploads'));
	},
	filename: function (req, file, cb) {
		// 解决中文乱码
		const original_name = Buffer.from(file.originalname, 'latin1').toString('utf8');
		cb(null, getDateTime(Date.now())[8] + '_' + Date.now() + '_' + original_name);
	}
});

const storageBatch = multer.diskStorage({
	destination: function (req, file, cb) {
		cb(null, path.join(__dirname, '../../public/uploads'));
	},
	filename: function (req, file, cb) {
		// 解决中文乱码
		const original_name = Buffer.from(file.originalname, 'latin1').toString('utf8');
		cb(null, original_name);
	}
});

const uploadSign = multer({ storage: storageSign });
const uploadBatch = multer({ storage: storageBatch });

// 文件夹名称
let ossDirectory = 'markdown';

router.post('/single', uploadSign.single('file'), async (req, res, next) => {
	try {
		let { size, mimetype, filename } = req.file;

		// markdown 文章中的图片，必须放到oss，这样加载才快
		let { type } = req.body;
		let fullUrl = null;
		if (type && type === 'markdown') {
			// 上传oss
			let { Location } = await cosUpload(ossDirectory, filename);
			fullUrl = 'https://' + Location;
		}

		res.send(
			ok({
				fullUrl,
				url: '/uploads/' + filename, //本地相对路径
				filename,
				size,
				type: mimetype
			})
		);
	} catch (error) {
		res.send(no(error));
	}
});

router.post('/batch', uploadBatch.array('file', 50), async (req, res, next) => {
	try {
		let { id, directoryName } = req.body;

		// 数据库，不能插入相同名字的照片
		let picsNames = [];
		let newFiles = [];

		// 数据库的相册的名称
		let [list] = await DB.query('select * from t_pic where albumId=?', [id]);

		list.forEach((item) => picsNames.push(path.basename(item.fullUrl)));
		req.files.forEach((item) => {
			if (!picsNames.includes(item.filename)) {
				newFiles.push(item);
			}
		});

		if (!newFiles.length) {
			return res.send(no('没有上传新的图片'));
		}

		// 放到相册的文件夹下面
		let name = 'album/' + directoryName;
		let { files } = await cosBatchUpload(name, newFiles);

		// 批量插入数据库
		await Promise.all(files.map((item) => DB.query('insert into t_pic ( albumId,fullUrl,filename) values(?,?,?)', [id, 'https://' + item.data.Location, path.basename(item.options.Key)])));

		res.send(ok());
	} catch (error) {
		res.send(no(error));
	}
});

module.exports = router;
